﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Top.Api;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using System.Data;
using System.Data.SqlClient;

namespace DBControl
{
    #region "Original Classes"
    /// <summary>
    /// 目标人群
    /// </summary>
    public class Group
    {
        #region "Fields and Properties"
        private long _groupid;
        private string _groupname;
        private string _groupdescription;

        public long GroupID { get { return _groupid; } set { _groupid = value; } }
        public string GroupName { get { return _groupname; } set { _groupname = value; } }
        public string GroupDescription { get { return _groupdescription; } set { _groupdescription = value; } }
        #endregion

        #region "Constructors"
        public Group()
        {
            this.GroupID = 0;
            this.GroupName = DBNull.Value.ToString();
            this.GroupDescription = DBNull.Value.ToString();
        }
        public Group(long gid, string gname, string gdescription)
        {
            this.GroupID = gid;
            this.GroupName = gname;
            this.GroupDescription = gdescription;
        }
        #endregion
    }
    /// <summary>
    /// 目标人群的集合
    /// </summary>
    public class Groups : CollectionBase
    {
        #region "Fileds and Properties"
        public Group this[int index] { get { return (Group)List[index]; } set { List[index] = value; } }
        public int Add(Group value) { return (List.Add(value)); }
        public int IndexOf(Group value) { return (List.IndexOf(value)); }
        public void Insert(int index, Group value) { List.Insert(index, value); }
        public void Remove(Group value) { List.Remove(value); }
        public bool Contrins(Group value) { return List.Contains(value); }
        #endregion "Fileds and Properties"
    }

    /// <summary>
    /// 定向优惠
    /// </summary>
    public class Bargain
    {
        #region "Fields and Properties"
        private long _bid;
        private string _bargaintitle;
        private string _discounttype;
        private string _discountvalue;
        private DateTime _end_date;
        private long _num_id;
        private long _groupid;
        private string _active;
        //private Int32 _decreasenum;

        public long Bid { get { return _bid; } set { _bid = value; } }
        public string BargainTitle { get { return _bargaintitle; } set { _bargaintitle = value; } }
        public string DiscountType { get { return _discounttype; } set { _discounttype = value; } }
        public string DiscountValue { get { return _discountvalue; } set { _discountvalue = value; } }
        public DateTime End_Date { get { return _end_date; } set { _end_date = value; } }
        public long Num_id { get { return _num_id; } set { _num_id = value; } }
        public long GroupID { get { return _groupid; } set { _groupid = value; } }
        public string Active { get { return _active; } set { _active = value; } }
        //public int DecreaseNum { get { return _decreasenum; } set { _decreasenum = value; } }
        #endregion

        #region "Constructors"
        /// <summary>
        /// 构造新的Bargains对象
        /// </summary>
        public Bargain()
        {
            this.Bid = 0;
            this.DiscountType = DBNull.Value.ToString();
            this.DiscountValue = DBNull.Value.ToString();
            this.End_Date = Convert.ToDateTime(DBNull.Value);
            this.BargainTitle = DBNull.Value.ToString();
            this.Num_id = 0 ;
            this.GroupID = Convert.ToInt32(DBNull.Value);
        }
        /// <summary>
        /// 构造新的Bargains对象
        /// </summary>
        /// <param name="bid"></param>
        /// <param name="distype"></param>
        /// <param name="disvalue"></param>
        /// <param name="enddate"></param>
        /// <param name="btitle"></param>
        /// <param name="numid"></param>
        /// <param name="gid"></param>
        /// <param name="active"></param>
        public Bargain(long bid, string distype, string disvalue, DateTime enddate, string btitle, long numid, long gid, string active)
        {
            this.Bid = 0;
            this.DiscountType = distype;
            this.DiscountValue = disvalue;
            this.End_Date = enddate;
            this.BargainTitle = btitle;
            this.Num_id = numid;
            this.GroupID = gid;
            this._active = active;
        }
        /// <summary>
        /// 构造新的Bargains对象
        /// </summary>
        /// <param name="promotion"></param>
        public Bargain( Promotion promotion )
        {
            this.Bid = promotion.PromotionId;
            this.BargainTitle = promotion.PromotionTitle;
            this.DiscountType = promotion.DiscountType;
            this.DiscountValue = promotion.DiscountValue;
            this.End_Date = Convert.ToDateTime(promotion.EndDate);
            this.Num_id = promotion.NumIid;
            this.GroupID = promotion.TagId;
            this.Active = promotion.Status;
        }
        #endregion
    }
    /// <summary>
    /// 定向优惠的集合
    /// </summary>
    public class Bargains : CollectionBase
    {
        #region "Fileds and Properties"
        public Bargain this[int index] { get { return (Bargain)List[index]; } set { List[index] = value; } }
        public int Add(Bargain value) { return (List.Add(value)); }
        public int IndexOf(Bargain value) { return (List.IndexOf(value)); }
        public void Insert(int index, Group value) { List.Insert(index, value); }
        public void Remove(Bargain value) { List.Remove(value); }
        public bool Contrins(Bargain value) { return List.Contains(value); }
        #endregion "Fileds and Properties"
    }
    #endregion "Originnal Classes"

    /// <summary>
    /// 市场营销
    /// </summary>
    public class Marketing
    {
        #region "Fields and Properties"
        private static ITopClient client = new DefaultTopClient(SystemLib.appurl, "12268933", "5c8fc265d41463b42f222d91f9f55fdf");
        private string sessionKey;
        public string errMsg;
        public static string GroupName = "EvoVIP";
        #endregion


        #region "Constructors"
        public Marketing(string sessionkey) { this.sessionKey = sessionkey; }
        #endregion "Constructors"

        #region "Event"
        /// <summary>
        /// 获得当前淘宝用户创建的所有人群
        /// </summary>
        /// <returns>Groups</returns>
        public Groups getTaobaoGroups() 
        {
            MarketingTagsGetRequest req = new MarketingTagsGetRequest();
            req.Fields = "tag_id,tag_name,create_date,description";
            MarketingTagsGetResponse response = client.Execute(req, sessionKey);
            Groups mygroups = new Groups();

            if (response.UserTags.Count != 0)
            {
                for (int i = 0; i < response.UserTags.Count; i++)
                {
                    Group mygr = new Group(response.UserTags[i].TagId, response.UserTags[i].TagName, response.UserTags[i].Description);
                    mygroups.Add(mygr);
                }               
            }
            return mygroups;
        }
        /// <summary>
        /// 获得当前淘宝用户创建的与条件相符的人群
        /// </summary>
        /// <param name="gid">要查询的人群id</param>
        /// <returns>Group</returns>
        public Group getTaobaoGroup(long gid)
        {
            MarketingTagsGetRequest req = new MarketingTagsGetRequest();
            req.Fields = "tag_id,tag_name,create_date,description";
            MarketingTagsGetResponse response = client.Execute(req, sessionKey);
            UserTag findtag = response.UserTags.Find(delegate(UserTag ut) { return ut.TagId == gid; });
            if (findtag == null)
            {
                return null;
            }
            else
            {
                Group mygrp = new Group(findtag.TagId, findtag.TagName, findtag.Description);
                return mygrp;
            }

        }
        /// <summary>
        /// 获得当前淘宝用户创建的与条件相符的人群
        /// </summary>
        /// <param name="gname">要查询的人群名</param>
        /// <returns>Group</returns>
        public Group getTaobaoGroup(string gname)
        {
            MarketingTagsGetRequest req = new MarketingTagsGetRequest();
            req.Fields = "tag_id,tag_name,create_date,description";
            MarketingTagsGetResponse response = client.Execute(req, sessionKey);
            UserTag findtag = response.UserTags.Find(delegate(UserTag ut) { return ut.TagName == gname; });
            if (findtag != null)
            {
                Group mygrp = new Group(findtag.TagId, findtag.TagName, findtag.Description);
                return mygrp;
            }
            else{ return null;}
        }
        /// <summary>
        /// 添加人群
        /// </summary>
        /// <param name="usnick">用户昵称</param>
        /// <returns>Boolean</returns>
        public Group addTaobaoGroup(string usnick) 
        {
            Group exsisgroup = getTaobaoGroup(GroupName);
            if (exsisgroup == null)//如果淘宝人群不存在
            {
                MarketingTagAddRequest req = new MarketingTagAddRequest();
                req.TagName = GroupName;
                req.Description = "EvoVIP会员";
                MarketingTagAddResponse response = client.Execute(req, sessionKey);
                if (response.IsError) { errMsg = response.ErrMsg; return null; }
                Group mygrp = new Group(response.UserTag.TagId, response.UserTag.TagName, response.UserTag.Description);
                try { addGroup(mygrp, usnick); }
                catch(Exception err){ errMsg = err.Message.ToString(); return null; }
                return mygrp;
            }
            else//如果淘宝人群存在
            {
                SqlDbHelper sdh = new SqlDbHelper();
                SqlDataReader dr = null;
                dr = sdh.ExecuteReader("select Tagid from Tag where Tagid = '" + exsisgroup.GroupID + "'");
                if (!dr.HasRows)//无记录
                {
                    try { addGroup(exsisgroup, usnick); }
                    catch (Exception err) { errMsg = err.Message.ToString(); return null; }
                }
                //else if (exsisgroup.GroupID != Convert.ToInt64(dr["Tagid"])) { addGroup(exsisgroup, usnick); }
                return exsisgroup;
            }
        }
        /// <summary>
        /// 删除当前用户下的指定人群
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <returns>Boolean</returns>
        public Boolean delTaobaoGroup(long gid)
        {
            MarketingTagDeleteRequest req = new MarketingTagDeleteRequest();
            req.TagId = Convert.ToInt64(gid);
            MarketingTagDeleteResponse response = client.Execute(req, sessionKey);
            if (response.IsError) { errMsg = response.ErrMsg; return false; }
            try { delGroup(gid); }
            catch (Exception err) { errMsg = err.Message.ToString(); return false; }
            return true;
        }
        /// <summary>
        /// 添加目标用户
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <param name="usnick">要添加的用户昵称</param>
        /// <returns></returns>
        public Boolean addTargetuser(long gid, string usnick)
        {
            MarketingTaguserAddRequest req = new MarketingTaguserAddRequest();
            req.TagId = gid;
            req.Nick = usnick;
            MarketingTaguserAddResponse response = client.Execute(req, sessionKey);
            if (response.IsError) { errMsg = response.ErrMsg; return false; }
            return true; 
        }
        /// <summary>
        /// 删除目标用户
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <param name="usnick">要删除的用户昵称</param>
        /// <returns></returns>
        public Boolean delTargetuser(long gid, string usnick)
        {
            MarketingTaguserDeleteRequest req = new MarketingTaguserDeleteRequest();
            req.TagId = gid;
            req.Nick = usnick;
            MarketingTaguserDeleteResponse response = client.Execute(req, sessionKey);
            if (response.IsError) { errMsg = response.ErrMsg; return false; }
            return true;
        }
        /// <summary>
        /// 获得当前用户创建的与条件相符的人群
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <returns></returns>
        public Group getGroup(long gid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            SqlDataReader dr = null;
            dr = sdh.ExecuteReader("select * from Tag where Tagid = " + gid);
            if (!dr.HasRows) { return null; }
            else
            {
                if (dr.Read())
                {
                    Group resualt = new Group(Convert.ToInt64(dr["Tagid"]), Convert.ToString(dr["Tagname"]), Convert.ToString(dr["TagDescription"]));
                    return resualt;
                }
                else { return null; }
            }
        }
        public Group getGroup(string usnick)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            SqlDataReader dr = null;
            dr = sdh.ExecuteReader("select * from Tag where Usnick = '" + usnick + "'");
            if (!dr.HasRows) { return null; }
            else
            {
                if (dr.Read())
                {
                    Group resualt = new Group(Convert.ToInt64(dr["Tagid"]), Convert.ToString(dr["Tagname"]), Convert.ToString(dr["TagDescription"]));
                    return resualt;
                }
                else { return null; }
            }
        }
        /// <summary>
        /// 添加Group
        /// </summary>
        /// <param name="addgrp">要添加的Group对象</param>
        /// <param name="usernick">所属的卖家昵称</param>
        /// <returns>Boolean</returns>
        protected Boolean addGroup(Group addgrp,string usernick)
        {
            SqlParameter[] sps = { new SqlParameter("@_tagid",addgrp.GroupID),
                                    new SqlParameter("@_tagname",addgrp.GroupName),
                                    new SqlParameter("@_description",addgrp.GroupDescription),
                                    new SqlParameter("@_usnick",usernick)};
            SqlDbHelper sdh = new SqlDbHelper();
            try
            {
                sdh.ExecuteNonQuery("modTag", CommandType.StoredProcedure, sps);
                return true;
            }
            catch (Exception err) { errMsg = err.Message.ToString(); return false; }
        }
        /// <summary>
        /// 删除当前用户下的人群
        /// </summary>
        /// <param name="gid">要删除的人群ID</param>
        /// <returns></returns>
        protected Boolean delGroup(long gid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            try { sdh.ExecuteNonQuery("delete from Tag where Tagid = " + Convert.ToInt64(gid)); }
            catch (Exception err) { errMsg = err.Message.ToString(); return false; }
            return true;
        }
        /// <summary>
        /// 添加定向优惠策略
        /// </summary>
        /// <param name="numid">商品ID</param>
        /// <param name="discountype">打折类型，可分为discount和price</param>
        /// <param name="discountvalue">折扣值，discount即为x.x形式的折扣率，price即为折扣后的价格</param>
        /// <param name="endtime">结束时间,格式为2011-01-01 12:00:00</param>
        /// <param name="gid">人群id</param>
        /// <returns></returns>
        public Bargain addTaobaoPromotion(string numid, string discountype, string discountvalue, DateTime endtime, long gid) 
        {
            MarketingPromotionAddRequest req = new MarketingPromotionAddRequest();
            req.NumIids = numid;
            req.DiscountType = discountype;
            req.DiscountValue = discountvalue;
            string stime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            req.StartDate = DateTime.Parse(stime);
            string etime = endtime.ToString("yyyy-MM-dd HH:mm:ss");
            req.EndDate = DateTime.Parse(etime);
            req.PromotionTitle = "EvoVIP会员折扣";
            req.TagId = gid;
            MarketingPromotionAddResponse response = client.Execute(req, sessionKey);
            if (response.IsError) { errMsg = response.ErrMsg; return null; }
            Bargains mybars = getTaobaoPromotion(gid, numid);
            foreach (Bargain mybar in mybars)
            {
                if (mybar.Bid == response.Promotions[0].PromotionId)
                {
                    return mybar;
                }
            }
            return null;
        }
        public Bargain addPromotion(Bargain bargain, Guid sellid)
        {
            SqlParameter[] sps = {new SqlParameter("@_pid", bargain.Bid),
                                    new SqlParameter("@_numid", bargain.Num_id),
                                    new SqlParameter("@_dtype", bargain.DiscountType),
                                    new SqlParameter("@_dvalue", bargain.DiscountValue),
                                    new SqlParameter("@_stime", DateTime.Now.ToString()),
                                    new SqlParameter("@_etime", bargain.End_Date.ToString()),
                                    new SqlParameter("@_ptitle", bargain.BargainTitle),
                                    new SqlParameter("@_sellid", sellid)};
            SqlDbHelper sdh = new SqlDbHelper();
            try { sdh.ExecuteNonQuery("setPromotion", CommandType.StoredProcedure, sps); }
            catch (Exception err) { this.errMsg = err.Message; return null; }
            return bargain;
        }
        /// <summary>
        /// 删除定向优惠策略
        /// </summary>
        /// <param name="pid">优惠策略ID</param>
        /// <returns></returns>
        public Boolean delPromotion(long pid)
        {
            MarketingPromotionDeleteRequest req = new MarketingPromotionDeleteRequest();
            req.PromotionId = pid;
            MarketingPromotionDeleteResponse response = client.Execute(req, sessionKey);
            if (response.IsError) { errMsg = response.ErrMsg; return false; }
            return true;
        }
        /// <summary>
        /// 根据商品和人群查询定向优惠策略
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <param name="numid">商品ID</param>
        /// <returns></returns>
        public Bargains getTaobaoPromotion(long gid, string numid) 
        {
            MarketingPromotionsGetRequest req = new MarketingPromotionsGetRequest();
            req.Fields = "promotion_id, promotion_title, num_iid, discount_type, discount_value, end_date, tag_id, status";
            req.TagId = gid;
            req.NumIid = numid;
            //req.Status = "ACTIVE";
            MarketingPromotionsGetResponse response = client.Execute(req, sessionKey);

            if (response.TotalResults != 0)
            {
                Bargains myBargains = new Bargains();
                for (int i = 0; i < response.Promotions.Count; i++)
			    {
                    myBargains.Add(new Bargain(response.Promotions[i]));
			    }  
                return myBargains;
            }
            return null;
        }    
        #endregion "Event"
    }
}
